use crate::controls::control_utils::show_messagebox;
use crate::controls::start::start_service;
use crate::controls::stop::stop_service;
use windows::Win32::UI::WindowsAndMessaging::{MB_ICONINFORMATION, MB_ICONWARNING};
use windows_service::Result;

/// 重启服务
pub fn restart_service() -> Result<()> {
    // 显示重启开始消息
    show_messagebox("重启服务", "正在重启服务，请稍候...", MB_ICONINFORMATION);

    // 先停止服务
    match stop_service() {
        Ok(_) => {
            // 服务已成功停止，现在启动服务
            match start_service() {
                Ok(_) => {
                    // 重启成功
                    show_messagebox("重启服务", "服务已成功重启！", MB_ICONINFORMATION);
                    Ok(())
                }
                Err(e) => {
                    // 启动失败
                    let error_code = match &e {
                        windows_service::Error::Winapi(io_error) => {
                            io_error.raw_os_error().unwrap_or(0) as u32
                        }
                        _ => 0,
                    };
                    show_messagebox(
                        "重启服务 - 错误",
                        &format!("服务已停止，但无法重新启动！错误代码: {}", error_code),
                        MB_ICONWARNING,
                    );
                    Err(e)
                }
            }
        }
        Err(e) => {
            // 停止失败
            let error_code = match &e {
                windows_service::Error::Winapi(io_error) => {
                    io_error.raw_os_error().unwrap_or(0) as u32
                }
                _ => 0,
            };
            show_messagebox(
                "重启服务 - 错误",
                &format!("无法停止服务，重启失败！错误代码: {}", error_code),
                MB_ICONWARNING,
            );
            Err(e)
        }
    }
}
